package com.dsz.usercenter.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsz.usercenter.common.BaseResponse;
import com.dsz.usercenter.common.ErrorCode;
import com.dsz.usercenter.common.ResultUtil;
import com.dsz.usercenter.exception.BusinessException;
import com.dsz.usercenter.model.domain.User;
import com.dsz.usercenter.model.request.UserLoginRequest;
import com.dsz.usercenter.model.request.UserRegisterRequest;
import com.dsz.usercenter.model.vo.UserVO;
import com.dsz.usercenter.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 用户接口
 */
@RestController
@RequestMapping("/user")
@CrossOrigin(origins = "http://127.0.0.1:5173", allowCredentials = "true")
public class UserController {
    @Resource
    private UserService userService;


    //以下为： 伙伴匹配系统的接口

    /**
     * 匹配用户
     * @param num 获取匹配用户的数量
     * @param request 请求
     * @return 匹配用户列表
     */
    @GetMapping("/match")
    public BaseResponse<List<UserVO>> matchUsers(Integer num, HttpServletRequest request) {
        num = Optional.ofNullable(num).orElse(10);
        if (num <= 0 || request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User currentUser = userService.getCurrentUser(request);
        List<UserVO> userVOList = userService.matchUsers(num, currentUser);
        return ResultUtil.ok(userVOList);
    }

    /**
     * 推荐用户
     * @param pageSize 页面大小
     * @param pageNum  第几页
     * @param request 请求
     * @return 推荐用户
     */
    @GetMapping("/recommend")
    public BaseResponse<List<User>> recommendUsers(int pageSize, int pageNum, HttpServletRequest request) {
        List<User> recommendUsers = userService.getRecommendUsers(pageSize, pageNum, request);
        return ResultUtil.ok(recommendUsers);
    }

    /**
     * 更新用户信息
     * @param user 待更新用户
     * @param request 请求
     * @return 是否更新成功 0 - 失败 1 - 成功
     */
    @PostMapping("/update")
    public BaseResponse<Integer> updateUser(@RequestBody User user, HttpServletRequest request) {
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        int res = userService.updateUser(user, request);
        return ResultUtil.ok(res);
    }

    /**
     * 根据标签搜索用户
     * @param tagNameList 标签集合
     * @return 用户集合
     */
    @GetMapping("/search/tags")
    public BaseResponse<List<User>> getUsersByTags(@RequestParam(required = false) List<String> tagNameList) {
        if (CollectionUtils.isEmpty(tagNameList)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "标签列表为空");
        }
        List<User> userList = userService.searchUserByTags_Memory(tagNameList);
        return ResultUtil.ok(userList);
    }


    //以下为： 用户中心的接口

    /**
     * 根据用户名查询用户
     * @param username 用户名
     * @param request 请求
     * @return 用户集合
     */
    @GetMapping("/search")
    public BaseResponse<List<User>> getUserList(String username, HttpServletRequest request) {
        //1.用户鉴权
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "不是管理员");
        }
        //2.根据用户名查询用户
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)) {
            queryWrapper.like("username", username);
        }
        List<User> list = userService.list(queryWrapper);
        List<User> userList = list.stream().map(item -> userService.getSafetyUser(item)).collect(Collectors.toList());
        return ResultUtil.ok(userList);
    }

    @PostMapping("/register")
    public BaseResponse<Long> userRegister(@RequestBody UserRegisterRequest userRegisterRequest) {
        if (userRegisterRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求体为空");
        }
        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword, planetCode)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        return userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
    }

    @PostMapping("/login")
    public BaseResponse<User> userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request) {
        if (userLoginRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求体为空");
        }
        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();
        if (StringUtils.isAnyBlank(userAccount, userPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数为空");
        }
        return userService.userLogin(userAccount, userPassword, request);
    }

    @PostMapping("/logout")
    public BaseResponse userLogout(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求对象为空");
        }
        return userService.userLogout(request);
    }

    /**
     * 根据id删除用户
     * @param id 用户id
     * @return 是否删除成功
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(Long id, HttpServletRequest request) {
        if (!userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH, "不是管理员");
        }
        if (id == null || id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号不存在");
        }
        boolean result = userService.removeById(id);
        return ResultUtil.ok(result);
    }

    /**
     * 返回当前登录用户信息
     * @param request 请求
     * @return 当前登录用户
     */
    @GetMapping("/currentUser")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request) {
        if (request == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        return ResultUtil.ok(userService.getCurrentUser(request));
    }
}
